const app = getApp();

Page({
  data: {
    id: '',
    product: null,
    loading: true,
    showLoginPopup: false,
    selectedSku: null,
    quantity: 1,
    cartCount: 0,
    priceDisplay: '0.00'
  },

  onLoad(options) {
    if (options.id) {
      this.setData({
        id: options.id,
        cartCount: app.globalData.cartCount
      });
      this.loadProductDetail();
    }

    // 监听购物车数量变化
    wx.eventBus.on('cartCountChanged', this.handleCartCountChanged);
  },

  onUnload() {
    // 页面卸载时移除监听
    wx.eventBus.off('cartCountChanged', this.handleCartCountChanged);
  },

  handleCartCountChanged(count) {
    this.setData({
      cartCount: count
    });
  },

  onShow() {
    this.loadCartCount();
  },

  async loadProductDetail() {
    try {
      const res = await app.request({
        url: `/product/products/${this.data.id}/`,
        method: 'GET'
      });
      console.log(res);
      if (res.code === 200 && res.data) {
        // 如果只有一个SKU，默认选中
        if (res.data.skus && res.data.skus.length === 1) {
          const sku = res.data.skus[0];
          this.setData({
            product: res.data,
            selectedSku: sku,
            priceDisplay: this.formatPrice(sku.price),
            loading: false
          });
        } else {
          // 多个SKU时，显示价格区间
          if (res.data.skus && res.data.skus.length > 0) {
            const prices = res.data.skus.map(sku => sku.price);
            const minPrice = Math.min(...prices);
            const maxPrice = Math.max(...prices);
            const priceDisplay = minPrice === maxPrice ? 
              this.formatPrice(minPrice) : 
              `${this.formatPrice(minPrice)} ~ ${this.formatPrice(maxPrice)}`;
            
            this.setData({
              product: res.data,
              priceDisplay: priceDisplay,
              loading: false
            });
          }
        }
      } else {
        wx.showToast({
          title: '商品信息加载失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('加载商品详情失败：', error);
      wx.showToast({
        title: '商品信息加载失败',
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  formatPrice(price) {
    return price.toFixed(2);
  },

  handleSelectSku(e) {
    const sku = e.currentTarget.dataset.sku;
    if (sku.stock <= 0) {
      return;
    }
    
    // 如果点击已选中的SKU，则取消选择
    if (this.data.selectedSku && this.data.selectedSku.id === sku.id) {
      this.setData({
        selectedSku: null,
        quantity: 1,
        priceDisplay: this.getDefaultPriceDisplay()
      });
    } else {
      // 选择新的SKU，重置数量为1，更新价格显示
      this.setData({
        selectedSku: sku,
        quantity: 1,
        priceDisplay: this.formatPrice(sku.price)
      });
    }
  },

  getDefaultPriceDisplay() {
    if (!this.data.product || !this.data.product.skus) {
      return '0.00';
    }
    const prices = this.data.product.skus.map(sku => sku.price);
    const minPrice = Math.min(...prices);
    const maxPrice = Math.max(...prices);
    return minPrice === maxPrice ? 
      this.formatPrice(minPrice) : 
      `${this.formatPrice(minPrice)} ~ ${this.formatPrice(maxPrice)}`;
  },

  async loadCartCount() {
    try {
      const res = await app.request({
        url: '/cart/count/',
        method: 'GET'
      });
      if (res.code === 200) {
        this.setData({
          cartCount: res.data.count
        });
      }
    } catch (error) {
      console.error('获取购物车数量失败：', error);
    }
  },

  handleQuantityInput(e) {
    let quantity = parseInt(e.detail.value);
    if (isNaN(quantity) || quantity < 1) {
      quantity = 1;
    }
    if (this.data.selectedSku && quantity > this.data.selectedSku.stock) {
      quantity = this.data.selectedSku.stock;
      wx.showToast({
        title: '超出库存数量',
        icon: 'none'
      });
    }
    this.setData({
      quantity: quantity
    });
  },

  handleDecreaseQuantity() {
    if (this.data.quantity <= 1) {
      return;
    }
    this.setData({
      quantity: this.data.quantity - 1
    });
  },

  handleIncreaseQuantity() {
    if (!this.data.selectedSku) {
      wx.showToast({
        title: '请先选择商品规格',
        icon: 'none'
      });
      return;
    }
    if (this.data.quantity >= this.data.selectedSku.stock) {
      wx.showToast({
        title: '超出库存数量',
        icon: 'none'
      });
      return;
    }
    this.setData({
      quantity: this.data.quantity + 1
    });
  },

  goToCart() {
    wx.switchTab({
      url: '/pages/cart/index/index'
    });
  },

  async handleAddToCart() {
    const token = wx.getStorageSync('token');
    if (!token) {
      this.showLoginPopup();
      return;
    }

    if (!this.data.selectedSku) {
      wx.showToast({
        title: '请选择商品规格',
        icon: 'none'
      });
      return;
    }

    if (this.data.selectedSku.stock <= 0) {
      wx.showToast({
        title: '商品库存不足',
        icon: 'none'
      });
      return;
    }

    try {
      const res = await app.request({
        url: '/cart/add/',
        method: 'POST',
        data: {
          sku_id: this.data.selectedSku.id,
          quantity: this.data.quantity
        }
      });

      if (res.code === 200) {
        wx.showToast({
          title: '已加入购物车',
          icon: 'success'
        });
        this.loadCartCount(); // 刷新购物车数量
      } else {
        wx.showToast({
          title: res.message || '添加失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('添加到购物车失败：', error);
      if (error.statusCode === 401) {
        this.showLoginPopup();
      } else {
        wx.showToast({
          title: '添加失败',
          icon: 'none'
        });
      }
    }
  },

  showLoginPopup() {
    this.setData({
      showLoginPopup: true
    });
  },

  hideLoginPopup() {
    this.setData({
      showLoginPopup: false
    });
  },

  goToLogin() {
    const currentPage = getCurrentPages().pop();
    const redirect = encodeURIComponent(`/pages/product/detail/detail?id=${this.data.id}`);
    wx.redirectTo({
      url: `/pages/login/login?redirect=${redirect}`
    });
  },

  handleBuyNow() {
    const token = wx.getStorageSync('token');
    if (!token) {
      this.showLoginPopup();
      return;
    }

    if (!this.data.selectedSku) {
      wx.showToast({
        title: '请选择商品规格',
        icon: 'none'
      });
      return;
    }

    if (this.data.selectedSku.stock <= 0) {
      wx.showToast({
        title: '商品库存不足',
        icon: 'none'
      });
      return;
    }

    const orderItems = [{
      sku_id: this.data.selectedSku.id,
      quantity: this.data.quantity,
      price: this.data.selectedSku.price,
      name: this.data.product.name,
      image: this.data.product.image,
      sku_name: this.data.selectedSku.name,
      total_price: this.data.selectedSku.price * this.data.quantity,
      spec_values: this.data.selectedSku.spec_values || []
    }];

    // 将订单信息存储到缓存中
    wx.setStorageSync('orderItems', orderItems);
    
    // 跳转到确认订单页面
    wx.navigateTo({
      url: '/pages/order/confirm/confirm?from=buy_now'
    });
  }
}); 